package com.example.yudaoly.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPointImpl;

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandlerImpl;
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 告诉springsecurity，使用我们自己的UserDetailsServiceImpl，
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 所有的请求都会被springSecurity拦截
     * 登录相关页面和处理器、静态资源需要放行
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭csrf 跨站请求伪造,前后端分离项目 就得 关闭
        http.csrf().disable();
//
//        //禁用springsecurity的会话管理
//        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 给相关请求放行
        http.authorizeRequests().antMatchers("/admin-api/system/auth/login","/login.html","/statics/*").permitAll();

        // 任何请求都要认证才能访问
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());

        // 把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


//         设置 授权异常和认证异常实现方式
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointImpl)
                .accessDeniedHandler(accessDeniedHandlerImpl);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }




}
